﻿using Dapper;
using Himp.TaskScheduling.Datas;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Options;
using System.Data;

namespace Himp.TaskScheduling.Hangfire.Jobs
{
    public class ZYOperateRecordJob : IHostedService
    {
        #region 字段

        private readonly ConnectionStringOption _connectionStrings;
        private ILogger<ZYOperateRecordJob> _logger;

        public const string GET_OPERATERECORD_SQL = @"
            SELECT 
            Id,
            Record,
            MachineCode,
            Person_ID AS PersonId,
            Name,
            DateTime
            FROM [dbo].[tb_ZY_OperateRecord]
            WHERE CONVERT(VARCHAR(10), [DateTime], 120) = CONVERT(VARCHAR(10), GETDATE(), 120)
            ";

        public const string EXIST_FLAG_SQL = @"
            SELECT CASE WHEN 
            EXISTS (SELECT 1 FROM [TaskScheduling].[TS_ZYOperateRecord] WHERE ID = @ID) 
            THEN 1 
            ELSE 0 
            END";

        public const string INSERT_OPERATERECORD_SQL = @"
            INSERT INTO [TaskScheduling].[TS_ZYOperateRecord]
            (
            Id,
            Record,
            MachineCode,
            PersonId,
            Name,
            DateTime
            )
            VALUES
            (
            @Id,
            @Record,
            @MachineCode,
            @PersonId,
            @Name,
            @DateTime
            )
            ";

        #endregion

        #region 方法

        public ZYOperateRecordJob(ILogger<ZYOperateRecordJob> logger
            , IOptions<ConnectionStringOption> connectionStrings)
        {
            _logger = logger;
            _connectionStrings = connectionStrings.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("--------启动:制样操作记录信息同步--------");
            _logger.LogInformation(_connectionStrings.SampleCabinet1);

            try
            {
                using (IDbConnection connection = new SqlConnection(_connectionStrings.KaiY_APS))
                {
                    connection.Open();
                    var operRecList = connection.Query<ZYOperateRecord>(GET_OPERATERECORD_SQL);

                    using (IDbConnection rlWebConnection = new SqlConnection(_connectionStrings.RL_Web))
                    {
                        foreach (var item in operRecList)
                        {
                            bool exists = await rlWebConnection.ExecuteScalarAsync<bool>(EXIST_FLAG_SQL,
                              new { ID = item.Id });

                            if (!exists)
                            {
                                await rlWebConnection.ExecuteAsync(INSERT_OPERATERECORD_SQL, item);
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogError(exception: e, "异常:制样操作记录信息同步");
            }

            _logger.LogInformation("--------完成:制样操作记录信息同步--------");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        #endregion
    }
}
